package com.example.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.UserEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    //定义两个参数来接收成功和失败的情况
    val loginSuccess = MutableLiveData<UserEntityResult>()
    val loginFail = MutableLiveData<String>()
    fun login(username:String,password :String){
        viewModelScope.launch {
           try {
               val map = mutableMapOf<String,String>()
               map["username"] = username
               map["password"] = password
               val json = Gson().toJson(map)
               val body = RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(),json)
               val result = apiServer.login(body)
               loginSuccess.value = result
           }catch (e:Exception){
               loginFail.value = e.message//请求失败
           }
        }
    }
}